package cn.tannn.ops.quartz.job;

import cn.tannn.ops.message.service.WebHookService;
import cn.tannn.ops.nginx.entity.Domains;
import cn.tannn.ops.nginx.service.DomainsService;
import cn.tannn.ops.quartz.annotation.Job;
import cn.tannn.ops.quartz.annotation.JobMeta;
import cn.tannn.ops.util.NginxUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

/**
 * 域名证书定时检测
 *
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @version V1.0
 * @date 2024/8/27 上午9:36
 * @see https://www.yuque.com/tanning/yg9ipo/bnug8bglppneik2r#qeIdb
 */
@Slf4j
@Component
@Job(cron = "0 5 0 * * ?", jobName = "DomainVerifySslJob", isStartNow = false)
@JobMeta(name = "域名证书有效期检测", description = "域名证书检测并更新元数据")
public class DomainVerifySslJob extends QuartzJobBean {

    private final DomainsService domainsService;

    public DomainVerifySslJob(DomainsService domainsService, WebHookService webHookService) {
        this.domainsService = domainsService;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.debug("Executing  DomainVerifySslJob");
        domainsService.findsWebHookDomainsValid().forEach(valid -> {
            try {
                Domains domains = NginxUtil.domainSslInfo(valid.getDomain());
                domains.setSslPath(valid.getSslPath());
                domains.setId(valid.getId());
                domains.setWebhookId(valid.getWebhookId());
                domains.setAccessId(valid.getAccessId());
                domains.setSshId(valid.getSshId());
                domainsService.saveOne(domains);
            } catch (Exception e) {
                log.error("检测域名有效期失败，域名{}，不合法/检测失败", valid.getDomain(), e);
            }
        });

    }
}
